package itsm.isperp.module.controller.app;

import itsm.isperp.framework.collection.tree.ITreeNode;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.domain.IBean;
import itsm.isperp.framework.domain.IRole;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.domain.UserStatus;
import itsm.isperp.framework.security.encoding.DESHelper;
import itsm.isperp.framework.utils.FileUtils;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.utils.ImageUtils;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.domain.CountQuery;
import itsm.isperp.framework.web.request.JqGridFilter;
import itsm.isperp.framework.web.request.JqGridFilterRule;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.dto.app.AppUserRoleDTO;
import itsm.isperp.module.dto.app.VAppUserRole;
import itsm.isperp.module.entity.app.AppDepartment;
import itsm.isperp.module.entity.app.AppRole;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.entity.customer.CusCustomer;
import itsm.isperp.module.service.app.AppDepartmentService;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.app.AppMessageSuccessService;
import itsm.isperp.module.service.app.AppRoleService;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.bpm.act.ActRuTaskService;
import itsm.isperp.module.service.customer.CusCustomerService;
import itsm.isperp.module.service.knowledge.KngKnowledgeItemService;
import itsm.isperp.module.utils.ProjectDomainUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 系统用户管理控制器
 * 
 * @author lizx
 * @date 2013-1-19
 * @version V1.0
 */
@Controller
@RequestMapping("/app/user")
public class AppUserController extends BaseController<AppUser> {

	/**
	 * 系统用户管理服务
	 */
	@Autowired
	protected AppUserService appUserService;

	@Autowired
	protected AppDictService appDictService;

	@Autowired
	protected AppRoleService appRoleService;

	@Autowired
	protected AppDepartmentService appDepartmentService;

	@Override
	public AppUserService getService() {
		return this.appUserService;
	}

	@Override
	public String getPageTitle() {
		return "系统用户";
	}

	@RequestMapping("getUserRoles")
	@ResponseBody
	public List<? extends IRole> getUserRoles(String username) {
		return this.appRoleService.findRolesByUsername(username);
	}

	/**
	 * 个人信息
	 * 
	 * @return
	 */
	@RequestMapping("profileView")
	public ModelAndView profileView() {
		ModelAndView mv = new ModelAndView();

		// 获取消息数目
		IUser u = ContextHolder.getLoginUser();

		Collection<? extends GrantedAuthority> roles = u.getAuthorities();
		String s = "";
		for (GrantedAuthority auth : roles) {
			s += ((VAppUserRole) auth).getName() + ",  ";
		}
		AppUser user = this.getService().findByUsername(u.getUsername());
		mv.addObject("currentUser", user);

		mv.addObject("userRoles", s);

		AppDepartment dept = this.appDepartmentService.findOne(user
				.getAppDepartmentId());
		if (dept != null) {
			mv.addObject("departmentName", dept.getTreenodeNamePath());
		}

		// 获取消息
		AppMessageSuccessService appMessageSuccessService = ContextHolder
				.getSpringBean("appMessageSuccessService");
		mv.addObject("newMessageTotal", appMessageSuccessService
				.findMyMessageCount(u.getUsername(), false));

		// mv.addObject("messageTotal",
		// appMessageReceiverService.findMyMessage(true).size());
		ActRuTaskService actRuTaskService = ContextHolder
				.getSpringBean("actRuTaskService");

		mv.addObject("workflowTaskTotal", actRuTaskService.getMyTaskCount());

		KngKnowledgeItemService kngKnowledgeItemService = ContextHolder
				.getSpringBean("kngKnowledgeItemService");
		JqGridFilter filter = new JqGridFilter();
		filter.addRule(new JqGridFilterRule("creator", JqGridFilterRuleOp.eq,
				ContextHolder.getLoginUsername()));

		filter.addRule(new JqGridFilterRule("process_id",
				JqGridFilterRuleOp.ne, ""));

		mv.addObject("knowledgeTotal",
				kngKnowledgeItemService.findAllCount(filter));

		mv.setViewName("app/user/profileView");
		return mv;
	}

	@RequestMapping("changePassword")
	@ResponseBody
	public ResultMessage changePassword(String oldPwd, String newPwd)
			throws Exception {
		return this.getService().changePassword(oldPwd, newPwd);

	}

	@RequestMapping("changeUserInfo")
	@ResponseBody
	public ResultMessage changeUserInfo(AppUser user) {
		return this.getService().changeUserInfo(user);
	}

	/**
	 * 重新设置个人头像
	 * 
	 * @return 设置个人头像页面
	 */
	@RequestMapping("photoEdit")
	public ModelAndView photoEdit(String id) {

		AppUser u = null;
		ModelAndView mv = this.getModelAndView();
		if (StringUtils.isEmpty(id)) {
			u = this.getService().findByUsername(
					ContextHolder.getLoginUsername());
		} else {
			u = this.getService().findOne(id);
			mv.addObject("id", id);
		}

		mv.addObject("photo", u.getPhoto());

		return mv;
	}
	
	@RequestMapping("personInfoEdit")
	public ModelAndView personInfoEdit(String id) {

		AppUser u = null;
		ModelAndView mv = this.getModelAndView();
		if (StringUtils.isEmpty(id)) {
			u = this.getService().findByUsername(
					ContextHolder.getLoginUsername());
		} else {
			u = this.getService().findOne(id);
			mv.addObject("id", id);
		}
		
		AppDepartment dept = this.appDepartmentService
				.findOne(u.getAppDepartmentId());
		if (dept != null) {
			mv.addObject("departmentName", dept.getTreenodeNamePath());
		}
		
		mv.addObject("deptName",
				dept == null ? null : dept.getTreenodeNamePath());

		mv.addObject("model", u);

		return mv;
	}
	
	@RequestMapping("passWordEdit")
	public ModelAndView passWordEdit(String id) {

		AppUser u = null;
		ModelAndView mv = this.getModelAndView();
		if (StringUtils.isEmpty(id)) {
			u = this.getService().findByUsername(
					ContextHolder.getLoginUsername());
		} else {
			u = this.getService().findOne(id);
			mv.addObject("id", id);
		}
		mv.addObject("model", u);

		return mv;
	}

	/**
	 * 
	 * @param x
	 * @param y
	 * @param x2
	 * @param y2
	 * @param w
	 * @param h
	 * @param imgId
	 * @param imgPath
	 * @param imgFileExt
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("saveUserPhoto")
	@ResponseBody
	public ResultMessage saveUserPhoto(String id, Integer x, Integer y,
			Integer x2, Integer y2, Integer w, Integer h, String imgPath,
			Integer width, Integer height) throws IOException {

		// 进行剪切图片操作

		String path = ContextHolder.getApplicationPath() + imgPath;

		File f = new File(path);
		if (!f.exists()) {
			return ResultMessage.failure("源文件不存在！");
		}

		String aImgPath = "global/img/users/"
				+ ContextHolder.getLoginUsername()
				+ FileUtils.getFileExtname(imgPath);

		String createImgPath = ContextHolder.getUploadFileStorePath()
				+ aImgPath;

		ImageUtils.abscut(path, createImgPath, x, y, w, h);

		AppUser user = null;
		if (StringUtils.isNotEmpty(id)) {
			user = new AppUser();
			user.setId(id);
		} else {
			user = (AppUser) ContextHolder.getLoginUser();
		}
		user.setPhoto(ContextHolder.getUploadFileStore() + aImgPath);

		Set<String> includeColumns = new java.util.HashSet<>();
		includeColumns.add("photo");
		this.getService().saveOrUpdateSpecific(user, includeColumns);
		return ResultMessage.success(createImgPath);

	}

	/**
	 * 菜单管理界面
	 * 
	 * @return 菜单管理界面视图
	 */
	@RequestMapping("edit")
	@Override
	public ModelAndView edit(String id, HttpServletRequest req) {

		ModelAndView mv = new ModelAndView(this.getModulePath() + "/edit");

		// 所属部门设置
		boolean areCustomer=false;
		String deptId = req.getParameter("deptId");
		String type=req.getParameter("type");
		AppDepartment dept = null;
		if(StringUtils.isEmpty(deptId))
		  deptId="";

		if (StringUtils.isNotEmpty(deptId)) {
			dept = this.appDepartmentService.findOne(deptId);
		}
		AppUser model = this.appUserService.findOne(id);
		List<AppRole> allRole = appRoleService.findAllRole();
		List<? extends IRole> haveRole = null;
		List<VAppUserRole> viewRole = new ArrayList<VAppUserRole>();

		if (model == null) {
			model = new AppUser();
			model.setId(HibernateUUIDGenerator.generate());
			model.setGender("男");
			model.setType("普通用户");
			model.setEnable(true);
			if(StringUtils.isNotBlank(type) && type.equals("customer"))
				areCustomer=true;
			// 设置部门的关联Id
			model.setAppDepartmentId(dept == null ? null : dept.getId());
			model.setAreCustomer(areCustomer);

			haveRole = new ArrayList<VAppUserRole>();

			for (AppRole role : allRole) {
				viewRole.add(new VAppUserRole(role));
			}

		} else {

			haveRole = this.appRoleService.findRolesByUsername(model.getName());

			dept = this.appDepartmentService
					.findOne(model.getAppDepartmentId());

			Map<String, VAppUserRole> map = new HashMap<String, VAppUserRole>();

			if (haveRole != null) {
				for (IRole i : haveRole) {
					map.put(i.getId(), (VAppUserRole) i);
				}

				for (AppRole role : allRole) {

					if (map.containsKey(role.getId())) {
						viewRole.add(map.get(role.getId()));
					} else {
						viewRole.add(new VAppUserRole(role));
					}

				}
				String[] selectRoles = new String[haveRole.size()];
				for (int i = 0; i < haveRole.size(); i++) {
					selectRoles[i] = haveRole.get(i).getId();
				}

				model.setSelectedRoles(selectRoles);
			}
			mv.addObject("isReadonly", true);
		}
		if(model.isAreCustomer())
			mv.addObject("userType", "customer");
		else
			mv.addObject("userType", "company");

		mv.addObject("deptName",
				dept == null ? null : dept.getTreenodeNamePath());
		mv.addObject("model", model);
		mv.addObject("deptId", deptId);
		// mv.addObject("viewRole", viewRole);
		mv.addObject("viewRole", allRole);
		mv.addObject("sex", appDictService.findByType("SEX"));
		
		IUser user = ContextHolder.getLoginUser();
    Collection<? extends GrantedAuthority> roles = user.getAuthorities();
    // 如果用户具有公司级数据权限，则不需要对数据进行过滤
    String showBtn = "1";
    int dataRange=ProjectDomainUtils.getUserMaxDataRange();
    if(dataRange==22 || dataRange==33)
      showBtn="0";
    mv.addObject("showBtn", showBtn);
		return mv;
	}
	
	@RequestMapping("savePortalUserInfo")
	@ResponseBody
	public ResultMessage savePortalUserInfo(AppUser model, HttpServletRequest req) {
		if (model.getUsername() != null) {
			model.setName(model.getUsername().trim());
		}
		this.appUserService.saveOrUpdate(model, req);
		return ResultMessage.success();
	}

	/**
	 * 保存实体
	 * 
	 * @param model
	 *            　一个继承与IBean接口的尸体　{@link IBean}
	 * @return json结果数据
	 */
	@RequestMapping("save")
	@ResponseBody
	public ResultMessage save(AppUser model, HttpServletRequest req) {

		// String[] roles = req.getParameterValues("roles");

		if (StringUtils.isEmpty(model.getAppDepartmentId())) {
			return ResultMessage.failure("所属组织不能为空");
		}
		String[] roles = model.getSelectedRoles();

		AppUserRoleDTO appUserRoleDTO = new AppUserRoleDTO(model);
		List<AppRole> rs = new ArrayList<AppRole>();

		if (model.getUsername() != null) {
			model.setName(model.getUsername().trim());
		}

		if (roles != null && StringUtils.isNotEmpty(model.getUsername())) {
			for (String r : roles) {
				AppRole role = new AppRole();
				role.setId(r);
				rs.add(role);
			}
		}
		String deptId=model.getAppDepartmentId();
		CusCustomerService cusCustomerService = ContextHolder.getSpringBean("cusCustomerService");
		Map<String,Object> m=cusCustomerService.getCustomerByRelateDeptId(deptId);
		if(m!=null)
		{
		  String customerName=m.get("name").toString();
	    String customerId=m.get("id").toString();
	    String category=m.get("category").toString();
	    model.setCustomerId(customerId);
	    model.setCustomerName(customerName);
	    if(category.equals("customer"))
	      model.setAreCustomer(true);
		}
		
		appUserRoleDTO.setRoles(rs);
		this.appUserService.saveOrUpdate(model, appUserRoleDTO, req);
		return ResultMessage.success();
	}
	
	@RequestMapping("saveBaseInfo")
  @ResponseBody
  public ResultMessage saveBaseInfo(AppUser model, HttpServletRequest req) {

    // String[] roles = req.getParameterValues("roles");

    if (StringUtils.isEmpty(model.getAppDepartmentId())) {
      return ResultMessage.failure("所属组织不能为空");
    }

    if (model.getUsername() != null) {
      model.setName(model.getUsername().trim());
    }

    
    if(model.getCustomerId()!=null)
    {
      CusCustomerService cusCustomerService = ContextHolder
          .getSpringBean("cusCustomerService");
      CusCustomer customer=cusCustomerService.findOne(model.getCustomerId());

      if(customer!=null)
      {
        String areCustomer=customer.getCategory();
        if(areCustomer.equals("customer"))
        {
          model.setAreCustomer(true);
        }
      }
    }

    this.appUserService.saveOrUpdate(model, req);
    return ResultMessage.success();
  }

	/**
	 * 用户查看界面
	 * 
	 * @return 用户查看界面
	 */
	@RequestMapping("view")
	public ModelAndView view(String id, HttpServletRequest req) {
		ModelAndView mv = this.getModelAndView();
		Map<String, Object> appUser = null;
		if (StringUtils.isNotEmpty(id)) {

			appUser = appUserService.findOneDetailById(id);
		} else {

			String username = req.getParameter("name");
			appUser = appUserService.findOneDetailByUsername(username);
		}

		if (appUser == null)
			appUser = appUserService.findOneDetailByUsername(id);
		mv.addObject("model", appUser);
		return mv;
	}

	@RequestMapping("status")
	@ResponseBody
	public ResultMessage status() {
		String status = this.getService().findUserStatus(
				ContextHolder.getLoginUsername());

		return ResultMessage.success(status);
	}

	@RequestMapping("restPassword/{id}")
	@ResponseBody
	public ResultMessage restPassword(@PathVariable("id") String id)
			throws Exception {
		this.getService().restPassword(id);
		return ResultMessage.success();
	}

	@RequestMapping("lock")
	@ResponseBody
	public void lock() {
		this.getService().updateUserStatus(UserStatus.locked,
				ContextHolder.getLoginUsername());
	}

	@RequestMapping("unlock")
	@ResponseBody
	public ResultMessage unlock(String unlockPassword) {
		IUser user = ContextHolder.getLoginUser();

		if (user == null) {
			return ResultMessage.failure("用户登录已超时");
		}
		if (StringUtils.isEmpty(unlockPassword)) {
			return ResultMessage.failure();
		}

		String pwd = user.getPassword();
		String pwd2 = null;

		try {
			pwd2 = DESHelper.encrypt(unlockPassword);
			if (pwd2.equals(pwd)) {

				this.getService().updateUserStatus(UserStatus.used,
						user.getUsername());
				return ResultMessage.success();
			}
			return ResultMessage.failure("密码错误！");
		} catch (Exception e) {
			return ResultMessage.failure(e);
		}

	}

	@RequestMapping("deptmentUser")
	@ResponseBody
	public PageResponse<Map<String, Object>> deptmentUser(
			JqGridRequest request, HttpServletRequest req) {

		String qtype = req.getParameter("qtype");
		String areCustomer=req.getParameter("type");
		String customerId=req.getParameter("customerId");
		if ("1".equals(qtype))
			request.addFilterRule("name", JqGridFilterRuleOp.in,
					"SELECT  app_user_name FROM app_user_role ur)");
		if(StringUtils.isNotBlank(areCustomer) && areCustomer.equals("company"))
			request.addFilterRule("are_customer", JqGridFilterRuleOp.eq,"0");
		else if(StringUtils.isNotBlank(areCustomer) && areCustomer.equals("customer"))
			request.addFilterRule("are_customer", JqGridFilterRuleOp.eq,"1");
		if(StringUtils.isNotBlank(customerId))
		{
		  request.addFilterRule("customer_id", JqGridFilterRuleOp.eq, customerId);
		}
		
		IUser user = ContextHolder.getLoginUser();
    int dataRange=ProjectDomainUtils.getUserMaxDataRange(user);
    boolean ifControl = false;
    if(dataRange==22 || dataRange==33)
      ifControl=true;
    if(ifControl)
    {
      String sql = "select app_department_id from app_user where name='"
          + user.getUsername() + "' and app_department_id is not null";
      JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
      List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
      if (list.size() > 0) {
        String deptId = list.get(0).get("app_department_id").toString();
        request.setSearchString(" b.treenode_path like '%"+deptId+"%'");
      }
      
    }
		return this.getListDetail(createStatusCountQuery(), request, req);

	}

	@RequestMapping("deptmentSysUser")
	@ResponseBody
	public PageResponse<Map<String, Object>> deptmentSysUser(
			JqGridRequest request, HttpServletRequest req) {

		String ifIncludeNoRoleUser = req.getParameter("ifIncludeNoRoleUser");
		String userNames=req.getParameter("userNames");
		String roleName = req.getParameter("rolenames");
		if (ifIncludeNoRoleUser.equals("false")) {
			if (StringUtils.isNotEmpty(roleName)) {

				String[] tempRoles = roleName.split(",");
				String inRolesStr = "(";
				for (String s : tempRoles) {
					inRolesStr += " b.name like '%"+s+"%' or";
				}
				inRolesStr=inRolesStr.substring(0,inRolesStr.length()-2)+")";
				
				request.addFilterRule(
						"name",
						JqGridFilterRuleOp.in,
						"SELECT  app_user_name FROM app_user_role a INNER JOIN	app_role b ON a.app_role_id=b.id AND "+inRolesStr);

			} else {
				request.addFilterRule("name", JqGridFilterRuleOp.in,
						"SELECT  app_user_name FROM app_user_role ");

			}

		}
		
		String projectIdForPrjMember=req.getParameter("projectIdForPrjMember");
		if(StringUtils.isNotEmpty(projectIdForPrjMember))
		{
			request.addFilterRule("name", JqGridFilterRuleOp.in,
					"SELECT app_user_name FROM proj_project_member where proj_project_id='"+projectIdForPrjMember+"'");
		}
		if(StringUtils.isNotEmpty(userNames))
		{
			String[] tempNames = userNames.split(",");
			String inNamesStr = "";
			for (String s : tempNames) {
				inNamesStr += "'"+s+"',";
			}
			inNamesStr=inNamesStr.substring(0,inNamesStr.length()-1);
			request.setSearchString(" a.name in("+inNamesStr+")");
		}
		request.addFilterRule("name", JqGridFilterRuleOp.isnotnull, "");
		if (!ifIncludeNoRoleUser.equals("false")) {
			return this.getService().findAllDetailByRequest(request).toPage();
		}else
		{
			return this.getListDetail(createStatusCountQuery(), request, req);
		}
		

	}

	@RequestMapping("userStatusMenu")
	@ResponseBody
	public ITreeNode[] userStatusMenu() {
		return this.createStatusCountQuery().getTreeNodes();

	}

	// 员工处理界面
	protected CountQuery createStatusCountQuery() {
		CountQuery cq = this.getService().createDefaultCountQuery();

		cq.addCountFilter("有效", true, "  a.enable=1 ");
		cq.addCountFilter("无效", true, "  a.enable=0 and (a.status<>'待审核' or a.status is null) ");
		cq.addCountFilter("待审核", true, "  a.enable=0 and a.status='待审核' ");

		return cq;
	}
	
	@RequestMapping("ifExistsUser")
	@ResponseBody
	public ResultMessage ifExistsUser(
			JqGridRequest request, HttpServletRequest req) {

		String name=req.getParameter("name");
		String id=req.getParameter("id");
		request.setSearchString(" name='"+name+"' and id<>'"+id+"'");
		AppUser u=this.getService().findOneByRequest(request);
		if(u==null)
		{
			return new ResultMessage(true,"");
		}else
		{
			return new ResultMessage(false,"用户名已存在！");
		}

	}
}
